package com.golden.procedure.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.golden.procedure.client.SiteClientApi;
import com.golden.procedure.domain.SiteDO;
import com.golden.procedure.query.SiteQueryDO;
import com.golden.procedure.result.ResultDO;
import com.golden.procedure.result.ResultSupport;
import com.golden.procedure.service.ISiteService;
import com.golden.procedure.util.BonConstant;

@Service("siteService")
public class SiteService extends BaseService implements ISiteService {

	@Autowired
	WorkSiteSchedulingService siteSchedulingService;

	@Autowired
	SiteClientApi siteClientApi;

	@Override
	public ResultDO query(SiteQueryDO query) {

		ResultSupport result = new ResultSupport();

		String region = "";
		if (StringUtils.isNotEmpty(query.getProvince())) {
			region = query.getProvince();
		}
		if (StringUtils.isNotEmpty(query.getCity())) {
			region = region + "_" + query.getCity();
		}

		// 查询上门组
		List<SiteDO> siteList = siteClientApi.query(BonConstant.SITE_TYPE_SMZ, region);

		if (null != siteList && siteList.size() > 0) {
			for (SiteDO siteDO : siteList) {
				siteDO = reset(siteDO);
				// 查询日期
				Date date = siteSchedulingService.getLatestSchedulingDate(siteDO.getId());
				if (null != date) {
					siteDO.setLatestSchDateStr(date.getTime() + "");
				}
			}
		} else {
			siteList = new ArrayList<SiteDO>();
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, siteList);
		return result;
	}

	@Override
	public ResultDO get(Integer id) {

		ResultDO result = new ResultSupport();
		// 1.基础数据验证
		if (isNumberInValid(id)) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误");
			result.setSuccess(false);
			return result;
		}
		SiteDO siteDO = siteClientApi.get(id);
		if (null == siteDO) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("数据不存在");
			result.setSuccess(false);
			return result;
		}

		siteDO = reset(siteDO);
		result.setModel(ResultDO.FIRST_MODEL_KEY, siteDO);
		return result;
	}

	public SiteDO reset(SiteDO siteDO) {
		if (null != siteDO) {
			siteDO.setName(siteDO.getSiteName());
			if (StringUtils.isNotEmpty(siteDO.getRegion())) {
				String[] regions = siteDO.getRegion().split("/");
				siteDO.setProvince((regions.length > 0 ? regions[0] : null));
				siteDO.setCity((regions.length > 1 ? regions[1] : null));
				siteDO.setDistrict((regions.length > 2 ? regions[2] : null));
			}
		}
		return siteDO;
	}

	@Override
	public String getName(Integer id) {

		// TODO:
		// if (!isNumberInValid(id)) {
		// SiteDO siteDO = siteClientApi.get(id);
		// if (null != siteDO) {
		// return siteDO.getSiteName();
		// }
		// }

		return "爱婴上门";
	}

}
